# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: chensili

import os

from coin.flow.archive import decompose_archive_filename
from coin.proto.coin_request_pb2 import (
    AccountRequestProto,
    ExchangeApiRequestProto)
from coin.proto.coin_log_pb2 import LogFileResponseProto


def _parse_topic_string(topic_string):
  topic_string = topic_string[1:] if topic_string.startswith('_') else topic_string
  market_type, exchange, api_version = topic_string.split('_')
  return market_type.capitalize(), exchange.capitalize(), api_version


def parse_file_name(file_name):
  topic_string, queue_name, queue_time = decompose_archive_filename(file_name)
  market_type, exchange, api_version = _parse_topic_string(topic_string)
  queue_time_str = queue_time.strftime('%Y%m%d-%H%M%SZ')
  _date, _time = queue_time_str.split('-')
  acct_req = AccountRequestProto(market_type=market_type, exchange=exchange, api_version=api_version)
  return LogFileResponseProto(type=LogFileResponseProto.SUBSCRIPTION_LOG,
                              log_file_name=file_name,
                              date=_date,
                              time=_time,
                              timestamp=queue_time_str,
                              acct_req=acct_req)


def enumerate_logs(request: ExchangeApiRequestProto, trading_date, log_dir):
  assert type(request) == ExchangeApiRequestProto
  trading_date = trading_date.strftime('%Y%m%d')
  files_dict = {}
  if not os.path.isdir(log_dir):
    return []
  for i, file_name in enumerate(os.listdir(log_dir)):
    resp = parse_file_name(file_name)
    if resp is None:
      continue
    if (resp.acct_req.market_type == request.market_type and
        resp.acct_req.exchange == request.exchange and
        resp.acct_req.api_version == request.api_version and
        resp.date == trading_date):
      files_dict[resp.timestamp] = os.path.join(log_dir, file_name)
  return [files_dict[key] for key in sorted(files_dict.keys())]
